package com.flybutter.usagelab.broadcast

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.flybutter.usagelab.repository.ScreenUsageInfo
import com.flybutter.usagelab.repository.getAppDataBase
import com.flybutter.usagelab.utils.executorService
import java.time.Duration
import java.time.LocalDateTime
import java.time.ZoneId
import java.util.*

/**
 * @author guojm
 * @date 2021/10/27
 */
class ScreenChangeReceiver : BroadcastReceiver() {
    val TAG = ScreenChangeReceiver::class.simpleName

    var lastTime: LocalDateTime = LocalDateTime.now()
    var lastScreen:Boolean  = true;

    override fun onReceive(context: Context, intent: Intent) {
        val screen = lastScreen
        val startTime = lastTime
        val endTime = LocalDateTime.now()
        lastScreen = intent.action == Intent.ACTION_SCREEN_ON
        lastTime = endTime
        val info = ScreenUsageInfo(UUID.randomUUID().toString(),
            if(screen) 1 else 0,
            startTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(),
            Duration.between(startTime,endTime).toMillis()
        )
        Log.d(TAG, "onReceive: $info")
        executorService.submit{
            context.getAppDataBase().getScreenUsageDao().insert(info)
        }
    }
}